import re

from SaaSDevelTool.data_mysql_data import db

"""  
数据操作
 
"""


# 定义一个函数，用于检查字符串是否为数字
def is_number(s):
    return bool(re.match("^\d+$", s))


# 分页组件
def paging_tool(page_number, page_size, table_name, table_id):
    """
        page_number:当前页数
        page_size:每页显示的页数
        page_size:表名：建议写全 比如 user表，写 "user_system.`user`"
        table_id:需要查询个数的 id 比如 user表，写 "user_id"

    调用方法示例:
        res = paging_tool(1, 10, "user_system.`user`", "user_id")

    示例响应 :
        {'totality': 130, 'page_number': 1, 'page_size': 10, 'limit_sql': 'LIMIT 0,10'}
        totality:数据总数
        page_number 第几页，相当于 page
        page_size   每页显示多少条数据
        limit_sql   返回拼接的sql

    调用示例 :
        res = paging_tool(1, 10, "user_system.`user`", "user_id")
        sql = "SELECT * FROM user {res["limit_sql"]}"
        #print("sql>>>>",sql)
        打印出来的 sql语句
        SELECT * FROM user LIMIT 0,10

    """
    # 定义 sql 语句，查询出所有数据
    query_sql = f"""
        SELECT
            count({table_id})
        FROM
            {table_name};"""
    totality = db.findOne(query_sql)
    # 获取总条数
    totality = totality[f'count({table_id})']
    initial = (page_number - 1) * page_size
    limit_sql = f"LIMIT {initial},{page_size}"
    return {"totality": totality, "page_number": page_number, "page_size": page_size, "limit_sql": limit_sql}


# RDS数据库分页
def paging_tool_join(query_sql: str, page_number: int, page_size: int):
    """
        分页函数
        :param query_sql:  查询的 sql语句
        :param page_number: 当前页数
        :param page_size:   当前页面数据

        :return: {'count': 数据总数, 'page_number': 当前页码, 'page_size': 每页显示条数, 'data': [分页的数据]
    """
    if page_number == 0:
        return {"count": 0, "page_number": page_number, "page_size": page_size, "data": []}
    # 使用正则表达式匹配 SELECT 和 FROM 之间的字符串
    match = re.search(r"(?<=SELECT\s).*?(?=\sFROM)", query_sql, flags=re.DOTALL | re.IGNORECASE)
    # 获取出来首个字段
    count_data = f"count(*)"
    # 定义查询总数的 sql
    count_sql_query = query_sql.replace(match.group(), count_data)
    # 获取总条数
    const_data = db.findOne(count_sql_query)
    if const_data == None:
        return {"count": 0, "page_number": page_number, "page_size": page_size, "data": []}
    const_data = const_data[count_data]
    # 定义sql 后缀 limit
    initial = (page_number - 1) * page_size
    limit_sql = f"LIMIT {initial},{page_size};"
    # 使用正则判断 sql语句里面是否存在 ;
    if re.search(r";", query_sql):
        query_sqls = query_sql.replace(";", "")
    else:
        query_sqls = query_sql
    query_data_sql = f"{query_sqls} {limit_sql}"
    # 查询出来对应的数据
    data = db.findAll(query_data_sql)
    return {"count": const_data, "page_number": page_number, "page_size": page_size, "data": data}
